//
//  RadioHomeController.m
//  EPA
//
//  Created by lanou3g on 16/4/27.
//  Copyright © 2016年 zlw. All rights reserved.
//

#import "RadioHomeController.h"
#import "RadioHomeCell.h"
#import "ZLWRadioHomeModel.h"
#import "ZLWRadioController.h"


#import "RadioCarouselModel.h"
#import "ZLWRadioHomeModel.h"
#import "LORefresh.h"
#import "CKCycleView.h"

@interface RadioHomeController ()
/**
 * 电台主题列表数据源
 */
@property (nonatomic, strong)NSMutableArray *DataSouces;
/**
 *  滚动视图列表数据源
 */
@property (nonatomic, strong) NSMutableArray *carouselArray;
/**
 * 滚动列表根视图
 */
@property (nonatomic, strong) UIView *headView;

@property (nonatomic, strong) CKCycleView *cycleScrollView;
/**
 *上拉请求开始位置
 */
@property (assign) NSInteger start;
/**
 *  每次请求的条数
 */
@property (assign) NSInteger limit;

/**
 *  header 属性
 */
@property (nonatomic, strong)LORefresh *headerRefresh;

@end

@implementation RadioHomeController

#pragma mark -懒加载，创建数据源容器-

- (NSMutableArray *)carouselArray
{
    if (_carouselArray == nil) {
        self.carouselArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _carouselArray;
}
- (NSMutableArray *)DataSouces {
    if (_DataSouces == nil) {
        self.DataSouces = [NSMutableArray arrayWithCapacity:0];
    }
    return _DataSouces;
}

-(void)dealloc
{
    [self.tableView removeObserver:[self.tableView gifHeader] forKeyPath:@"contentOffset"];
    [self.tableView removeObserver:[self.tableView defaultFooter] forKeyPath:@"contentOffset"];
    [self.tableView removeObserver:[self.tableView defaultFooter] forKeyPath:@"contentOffSize"];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
  
   [self reloadNetWorking];
    [self reloadMoreData];
    
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    __weak typeof(self)weakSelf = self;
    [self.tableView addRefreshWithRefreshViewType:LORefreshViewTypeHeaderDefault refreshingBlock:^{
        [weakSelf.DataSouces removeAllObjects];
        [weakSelf reloadMoreData];
        [weakSelf.tableView reloadData];
    }];
    self.headerRefresh = [self.tableView gifHeader];
    [self.headerRefresh setGifName:@"wangnima"];

    //下拉刷新
    [self.tableView addRefreshWithRefreshViewType:LORefreshViewTypeFooterDefault refreshingBlock:^{
        [weakSelf reloadMoreData];
    }];

    
    [self.tableView registerNib:[UINib nibWithNibName:@"RadioHomeCell" bundle:nil] forCellReuseIdentifier:@"radiohomecell"];
  
}

#pragma mark -数据请求-
-(void)reloadNetWorking
{
    [ZLW_NetWorkRequestManager requestURL:[NSURL URLWithString:RADIOLIST_URL] Method:CK_POST Params:@{@"client":@"1",@"deviceid":@"63A94D37-33F9-40FF-9EBB-481182338873",@"auth":@"",@"version":@"3.0.2", @"limit":[NSString stringWithFormat:@"%ld", _limit]} Result:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (data) {
            NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
            
            // 获取滚动列表数据
            NSArray *carouselArr = dataDic[@"data"][@"carousel"];
            for (NSDictionary *dic in carouselArr) {
                RadioCarouselModel *model = [[RadioCarouselModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                NSLog(@"%@",model);
                [self.carouselArray addObject:model];
            }
            
            // 获取电台主题列表数据
            NSArray *alllistArr = dataDic[@"data"][@"alllist"];
            for (NSDictionary *dic in alllistArr) {
                ZLWRadioHomeModel *model = [[ZLWRadioHomeModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.DataSouces addObject:model];
            }

            dispatch_async(dispatch_get_main_queue(), ^{
                  // 刷新主题列表
                [self.tableView reloadData];
                [[self.tableView gifHeader] endRefreshing];
                [[self.tableView defaultFooter] endRefreshing];
            });
        
        }
            }];
}

-(void)reloadMoreData
{
    [ZLW_NetWorkRequestManager requestURL:[NSURL URLWithString:RADIOMLISTORE_URL] Method:CK_POST Params:@{@"client":@"1",@"deviceid":@"63A94D37-33F9-40FF-9EBB-481182338873",@"auth":@"", @"start":[NSString stringWithFormat:@"%ld", _start], @"limit":[NSString stringWithFormat:@"%ld", _limit]} Result:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        
        // 获取电台主题列表数据
        NSDictionary *alllistArr = dataDic[@"data"][@"list"];
        for (NSDictionary *dic in alllistArr) {
            ZLWRadioHomeModel *model = [[ZLWRadioHomeModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.DataSouces addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
//            [[self.tableView gifHeader] endRefreshing];
//            [[self.tableView defaultFooter] endRefreshing];
        });

    }];
}


#pragma mark -创建列表视图-

//创建轮播图
- (void)creatCycleScrollView {
    NSLog(@"轮播图！！！");
    _cycleScrollView = [[CKCycleView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth , 230) interVal:3];
    NSMutableArray *viewsArray = [@[] mutableCopy];
    for (int i = 0; i < _carouselArray.count; ++i) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:_cycleScrollView.bounds];
        RadioCarouselModel *model = _carouselArray[i];
        [imageView sd_setImageWithURL:[NSURL URLWithString:model.img]];
        [viewsArray addObject:imageView];
    }
    
    __weak NSArray *carouseArr = _carouselArray;
    __weak  RadioHomeController *radioVC = self;
    [_cycleScrollView addTapBlock:^(NSInteger index) {
        NSLog(@"当前点击%ld页",(long)index);
        RadioCarouselModel *model = [carouseArr objectAtIndex:index];
        NSLog(@"url = %@",model.url);
        NSArray *cArray = [model.url componentsSeparatedByString:@"/"];
        
        ZLWRadioHomeModel *modelH = [[ZLWRadioHomeModel alloc] init];
        modelH.radioid = [cArray lastObject];
        ZLWRadioController *radiodetailVC = [[ZLWRadioController alloc] init];
        radiodetailVC.radioAllarysModel = modelH;
        [radioVC.navigationController pushViewController:radiodetailVC animated:YES];
    }];
//    [self.headView addSubview:_cycleScrollView];
   
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return self.DataSouces.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    RadioHomeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"radiohomecell" forIndexPath:indexPath];
   
    cell.model = self.DataSouces[indexPath.row];
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 200;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZLWRadioController *radioVC = [[ZLWRadioController alloc] init];
    radioVC.radioAllarysModel = self.DataSouces[indexPath.row];
    [self.navigationController pushViewController:radioVC animated:YES];
    
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
